package com.copm.ifm.message.send;

import com.alibaba.fastjson.JSONObject;
import com.copm.ifm.base.basic.exception.ServiceException;
import com.copm.ifm.message.entity.SendTemplateDto;
import com.copm.ifm.message.entity.StaffReceive;
import com.copm.ifm.message.msg.IMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;

/**
 * @author 86131
 */
@Slf4j
public class EMSSend implements IMessage {

    private final RestTemplate restTemplate = new RestTemplate();
    private static final String URL = "http://client.sms10000.com/api/webservice";
    private static final String EPR_ID = "619";
    private static final String USER_ID = "xhwlifm";
    private static final String PASSWORD = "xhifm2019";
    private static final String USERS = "13147024600";

    @Override
    public void send(SendTemplateDto<StaffReceive> sendTemplateDto, List<StaffReceive> users) {
        long timeStamp = System.currentTimeMillis();
        int msgId = (int) timeStamp;
        int verifyCode = new Random().nextInt(899999) + 100000;
        String content = null;
        try {
            content = URLEncoder.encode(sendTemplateDto.getContent(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new ServiceException("短信发送错误，错误内容为：" + e.getMessage());
        }
        String keyStr = EPR_ID + USER_ID + PASSWORD + timeStamp;
        String key = md5(keyStr);
        String postUrl = URL + "?format=1&cmd=send&eprId=" + EPR_ID + "&userId=" + USER_ID + "&key=" + key +
                "&timestamp=" + timeStamp + "&msgId=" + msgId + "&mobile=" + USERS + "&content=" + content + "";
        String res = restTemplate.postForObject(postUrl, null, String.class);
        JSONObject json = JSONObject.parseObject(res);
        String result = json.get("result").toString();
        if (StringUtils.isEmpty(result) || Integer.parseInt(result) != 1) {
            log.info("请求失败：{}", result);
        }
    }

    public static String md5(String content) {
        String res = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(content.getBytes());
            byte[] digest = md.digest();
            int i;
            StringBuilder buf = new StringBuilder("");
            for (byte b : digest) {
                i = b;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            res = buf.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return res;
    }
}
